package com.lipaluma.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.lipaluma.exceptions.CsvParserException;

/**
 * Utility class for XML
 * @author mario.soares
 */
public class XmlUtils {

	/**
	 * parse an Xml document for the entry {@link InputStream}
	 * @param in the inputStream of the xml file
	 * @return the root element
	 */
	public static Element parseXmlFileConfiguration(InputStream in) {
		Element element;
		try {
			element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in).getDocumentElement();
		} catch (SAXException e) {
			throw new CsvParserException("The xml file is mal formatted", e);
		} catch (IOException e) {
			throw new CsvParserException("The xml file can't be read", e);
		} catch (ParserConfigurationException e) {
			throw new CsvParserException( "A parsing error occured on reading the xml file", e);
		}
		return element;
	}

	/**
	 * parse an Xml document for the entry {@link InputStream}
	 * @param in the inputStream of the xml file
	 * @return the root element
	 */
	public static Element parseXmlFileConfiguration(Reader reader) {
		Element element;
		try {
			InputSource source = new InputSource(reader);
			element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(source).getDocumentElement();
		} catch (SAXException e) {
			throw new CsvParserException("The xml file is mal formatted", e);
		} catch (IOException e) {
			throw new CsvParserException("The xml file can't be read", e);
		} catch (ParserConfigurationException e) {
			throw new CsvParserException( "A parsing error occured on reading the xml file", e);
		}
		return element;
	}

}
